#include <stdlib.h>


#include "ch.h"
#include "hal.h"
#include "chprintf.h"

#include "myADC.h"

/*
 * Defines for continuous scan conversions
 */
#define ADC_GRP1_NUM_CHANNELS   4
#define ADC_GRP1_BUF_DEPTH      4
static adcsample_t samples[ADC_GRP1_NUM_CHANNELS * ADC_GRP1_BUF_DEPTH];

unsigned long dataX, dataY;

static const ADCConversionGroup adcgrpcfg1 = {
  TRUE,                     //circular buffer mode
  ADC_GRP1_NUM_CHANNELS,    //Number of the analog channels
  NULL,              //Callback function
  NULL,         //Error callback
  0,                        /* CR1 */
  0, //ADC_CR2_SWSTART,          /* CR2 */
  0,  //sample times ch10-18
  ADC_SMPR2_SMP_AN1(ADC_SAMPLE_239P5) | ADC_SMPR2_SMP_AN2(ADC_SAMPLE_239P5),   //sample times ch0-9
  ADC_SQR1_NUM_CH(ADC_GRP1_NUM_CHANNELS),                                   //SQR1: Conversion group sequence 13...16 + sequence length
  0 , //SQR2: Conversion group sequence 7...12
  ADC_SQR3_SQ1_N(ADC_CHANNEL_IN1) | ADC_SQR3_SQ2_N(ADC_CHANNEL_IN2) |     //SQR3: Conversion group sequence 1...6
	ADC_SQR3_SQ3_N(ADC_CHANNEL_IN0) | ADC_SQR3_SQ4_N(ADC_CHANNEL_IN4)
};


/*
 * print the values
 */
void cmd_measureRead(BaseSequentialStream *chp, int argc, char *argv[]) {
	int i;
  (void)argc;
  (void)argv;

	while(1) {
	dataX=dataY=0;
	for (i=0; i<ADC_GRP1_BUF_DEPTH; i++) {
		dataX += samples[i*ADC_GRP1_NUM_CHANNELS];
		dataY += samples[i*ADC_GRP1_NUM_CHANNELS+1];
	}
	
	dataX /= ADC_GRP1_BUF_DEPTH;
	dataY /= ADC_GRP1_BUF_DEPTH;

	chprintf(chp, "val1 %ld  val2 %ld\r\n", dataX, dataY);
	chThdSleepMilliseconds(300);
	}
}

unsigned long ADC_get(int ch) {
	int i;
	unsigned long ret;
	if (ch>=ADC_GRP1_NUM_CHANNELS) return 0;
	ret = 0;
	for (i=0; i<ADC_GRP1_BUF_DEPTH; i++) {
		ret += samples[i*ADC_GRP1_NUM_CHANNELS+ch];
	}
	ret /= ADC_GRP1_BUF_DEPTH;
	return ret;
}

void myADCinit(void){
  adcStart(&ADCD1, NULL);
	adcStartConversion(&ADCD1, &adcgrpcfg1, samples, ADC_GRP1_BUF_DEPTH);
}
